package com.tg.service.eventbus2.springconfig;

import com.google.common.collect.Lists;
import com.tg.service.eventbus2.Component;
import com.tg.service.eventbus2.component.CheckGroupCp;
import com.tg.service.eventbus2.component.FirstLoginCp;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.util.List;

public class ImportEngineBeanDefinition implements ImportBeanDefinitionRegistrar {

    private static final List<String> EVENT_BUS = Lists.newArrayList(
            "Login",
            "Pay"
    );

    private static final List<Class<?>> CPS = Lists.newArrayList(
            FirstLoginCp.class,
            CheckGroupCp.class
    );

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

        for (String eventBus : EVENT_BUS) {
            BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(EventBusFactoryBean.class);
            BeanDefinition beanDefinition = builder.getBeanDefinition();
            beanDefinition.setAutowireCandidate(true);
            beanDefinition.setLazyInit(false);

            registry.registerBeanDefinition(eventBus + EventBusFactoryBean.class.getSimpleName(), beanDefinition);
        }

        for (Class<?> cp : CPS) {
            BeanDefinitionBuilder builder2 = BeanDefinitionBuilder.genericBeanDefinition(ComponentFactoryBean.class);
            BeanDefinition beanDefinition2 = builder2.getBeanDefinition();
            beanDefinition2.setAutowireCandidate(true);
            beanDefinition2.setLazyInit(false);
            beanDefinition2.setDependsOn("loadUserService");

            registry.registerBeanDefinition(cp.getSimpleName(), beanDefinition2);
        }
    }
}
